#include "data.h"

namespace lps {
  bool dataFile::read(std::string file, // readin file name
		      char delim,       // , or space as delimiter
		      bool header) {    // whether there is header in the file  
    try {
      std::ifstream readin;
      readin.open(file.c_str());
      std::string line;
      // read header if there are
      if (header) {
	std::size_t pos, prev = 0;
	getline(readin, line);
	while (1) {
	  pos = line.find(delim, prev);
	  std::string word(line, prev, pos - prev);
	  prev = pos + 1;
	  names.push_back(word);
	  if (pos == std::string::npos)
	    break;
	}
      }
      
      // read in the data from file
      unsigned numCol = 0;
      while(readin.good()) {
	getline(readin, line);
	if (line.size() > 0 ) {
	  if (numCol <= 0) {
	    std::vector<std::string> tmp; 
	    std::size_t pos, prev = 0;
	    while (1) {
	      pos = line.find(delim, prev);
	      std::string word(line, prev, pos - prev);
	      prev = pos + 1;
	      tmp.push_back(word);
	      if (pos == std::string::npos) {
		numCol = tmp.size();
		break;
	      }
	    }
	  }
	  std::size_t pos, prev = 0;
	  arma::rowvec tmp(numCol);
	  for (unsigned j = 0; j < numCol; j++) {
	    pos = line.find(delim, prev);
	    std::string word(line, prev, pos - prev);
	    prev = pos + 1;
	    tmp(j) = atof(word.c_str());
	  }
	  input = join_cols(input, tmp);	
	}
      }
    } catch( char *str )    {
      std::cout << "Caught some other exception: " << str << std::endl;
    }
    return 1;
  }
} // namespace lps
